package cn.zmit.kuxi.activity;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import cn.zmit.kuxi.R;
import cn.zmit.kuxi.activity.binner.SliderBanner;
import cn.zmit.kuxi.adapter.MainSliderBannerOne;
import cn.zmit.kuxi.event.EventFactory;
import cn.zmit.kuxi.request.RequestTask;
import cn.zmit.kuxi.widget.PtrHeader;

import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.xdroid.common.utils.ScreenUtils;
import com.xdroid.common.utils.ToastUtils;
import com.xdroid.functions.request.JsonData;
import com.xdroid.request.extension.XDroidRequest;
import com.xdroid.request.extension.config.DataType;
import com.xdroid.request.extension.impl.OnRequestListenerAdapter;
import com.xdroid.widget.ptr.PtrDefaultHandler;
import com.xdroid.widget.ptr.PtrFrameLayout;
import com.xdroid.widget.ptr.PtrHandler;

/** * @author @parameter * @return */
public class JoinDetailActivity extends BaseActivity {

	/**
	 * 装ImageView数组
	 */
	private ImageView[] mImageViews;
	private List<String> strings;

	@ViewInject(R.id.tv_title_join)
	private TextView tv_title_join;
	@ViewInject(R.id.tv_detail_data)
	private TextView tv_detail_data;
	@ViewInject(R.id.tv_introduction)
	private TextView tv_introduction;
	@ViewInject(R.id.progressBarPeople)
	private ProgressBar progressBarPeople;
	@ViewInject(R.id.tv_allPeople)
	private TextView tv_allPeople;
	@ViewInject(R.id.tv_alreadyJoin)
	private TextView tv_alreadyJoin;
	@ViewInject(R.id.tv_joinNum)
	private TextView tv_joinNum;
	@ViewInject(R.id.tv_winProbability)
	private TextView tv_winProbability;
	@ViewInject(R.id.tv_luckNum)
	private TextView tv_luckNum;
	@ViewInject(R.id.btn_nowJoin)
	private Button btn_nowJoin;
	@ViewInject(R.id.btn_joinCarts)
	private Button btn_joinCarts;
	@ViewInject(R.id.tv_join_user)
	private TextView tv_join_user;
	@ViewInject(R.id.rl_doing)
	private RelativeLayout rl_doing;
	@ViewInject(R.id.rl_done)
	private RelativeLayout rl_done;
	@ViewInject(R.id.btn_Join_next)
	private RelativeLayout btn_Join_next;
	private String title, goodsName, joinNeed, joinCount, myJoin, userId,
			gp_id;// 存放上个界面传过来的各种值
	private String lucky = "";
	double result;
	String introduct;

	@ViewInject(R.id.slider_banner)
	private SliderBanner sliderBanner;
	/**
	 * 轮播图控制器
	 */
	private MainSliderBannerOne mainSliderBanner;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setTitleView("参与详情", true);
		setContentView(R.layout.activity_join_detail);
		ViewUtils.inject(this);
		initVIew();
		initPtr();
		initSliderBanner();
		tv_join_user.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				Bundle bundle2 = new Bundle();
				bundle2.putString("gp_id", getTextFromBundle("gp_id"));
				openActivity(JoinUserActivity.class, bundle2);
			}
		});
	}

	// 下拉刷新
	@ViewInject(R.id.ptr_view)
	private PtrFrameLayout ptr_view;
	private PtrHeader ptrHeader;
	public String next_gp_id;

	// 初始化下拉刷新
	private void initPtr() {
		/* 创建自定义刷新头部view */
		ptrHeader = new PtrHeader(this);
		/* 设置刷新头部view */
		ptr_view.setHeaderView(ptrHeader);
		/* 设置回调 */
		ptr_view.addPtrUIHandler(ptrHeader);
		/* 横向拉动时，禁止下拉 */
		ptr_view.disableWhenHorizontalMove(true);
		// 设置监听
		ptr_view.setPtrHandler(new PtrHandler() {

			@Override
			public void onRefreshBegin(PtrFrameLayout frame) {
				frame.postDelayed(new Runnable() {

					@Override
					public void run() {
						getData();
					}
				}, 500);
			}

			@Override
			public boolean checkCanDoRefresh(PtrFrameLayout frame,
					View content, View header) {
				return PtrDefaultHandler.checkContentCanBePulledDown(frame,
						content, header);
			}
		});
		/* 延时100hao秒,自动刷新 */
		ptr_view.postDelayed(new Runnable() {

			@Override
			public void run() {
				ptr_view.autoRefresh();
			}
		}, 100);
	}

	@SuppressWarnings("deprecation")
	private void initVIew() {// 初始化view
//		 title = getTextFromBundle("title");
//		 goodsName = getTextFromBundle("goodsName");
		// joinNeed = getTextFromBundle("joinNeed");
		// joinCount = getTextFromBundle("joinCount");
		// myJoin = getTextFromBundle("my_join");
		// goodsName = getTextFromBundle("goodsName");
		// userId = getTextFromBundle("userId");
		// userid = PreferenceHelper.readString(context,
		// SPConstants.SHARED_PREFERENCE_NAME, SPConstants.USERID, "");
		gp_id = getTextFromBundle("gp_id");
		// tv_title_join.setText("第" + title + "期");
		// tv_detail_data.setText(goodsName);
		// tv_allPeople.setText("总需人数：" + joinNeed + "人");
		// tv_alreadyJoin.setText("已参与：" + joinCount + "人");
		// tv_joinNum.setText("本次参与：" + myJoin + "次");
		// double my = Integer.parseInt(myJoin);
		// double all = Integer.parseInt(joinNeed);
		// double join = Integer.parseInt(joinCount);
		// result = (join / all) * 100;
		// progressBarPeople.setMax(100);
		// progressBarPeople.setProgress((int) result);
		// double winProbability = (my / all) * 100;
		// String win = String.format("%.2f", winProbability);// 转化保留两位小数
		// tv_winProbability.setText("中奖概率：" + win + "%");

	}

	/**
	 * 初始化轮播图
	 */
	private void initSliderBanner() {
		RelativeLayout.LayoutParams lyp = new RelativeLayout.LayoutParams(
				ScreenUtils.getScreenWidth(context),
				(int) (ScreenUtils.getScreenWidth(context) * 1f / 16 * 9.6f));
		sliderBanner.setLayoutParams(lyp);
		mainSliderBanner = new MainSliderBannerOne(sliderBanner);
	}

	private void getData() {

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("user_id", userid);
		RequestTask.getInstance().doJoinDetails(this, gp_id, map,
				new onRequestListener());
	}

	private class onRequestListener extends OnRequestListenerAdapter<Object> {
		@Override
		public void onDone(XDroidRequest<?> request, String response,
				DataType dataType) {
			super.onDone(request, response, dataType);

			JsonData jsonData = JsonData.create(response);
			JsonData goods_info = jsonData.optJson("goods_info");
			String my_buy_count = jsonData.optString("my_buy_count");
			next_gp_id = jsonData.optString("next_gp_id");
			// Log.e("xx1",my_buy_count+"");
			String my_sole_numbers = jsonData.optString("my_sole_numbers");
			if (goods_info != null && goods_info.length() > 0) {

				// tv_title_join.setText("第" + title + "期");
				// tv_detail_data.setText(goodsName);
				// tv_allPeople.setText("总需人数：" + joinNeed + "人");
				// tv_alreadyJoin.setText("已参与：" + joinCount + "人");
				// tv_joinNum.setText("本次参与：" + myJoin + "次");
				title=goods_info.optString("phase");
				goodsName=goods_info.optString("name");
				joinNeed = goods_info.optString("price");
				joinCount = goods_info.optString("buy_count");
				introduct = goods_info.optString("description");
				mainSliderBanner.play(goods_info.optJson("banner"), true);
				tv_introduction.setText(introduct);
				tv_detail_data.setText(goods_info.optString("name"));
				tv_allPeople.setText("总需人数：" + joinNeed);
				tv_alreadyJoin.setText("已参与：" + joinCount);
				tv_title_join
						.setText("第" + goods_info.optString("phase") + "期");
				double my = Integer.parseInt(my_buy_count);
				double all = Integer.parseInt(goods_info.optString("price"));
				double join = Integer.parseInt(goods_info
						.optString("buy_count"));
				tv_joinNum.setText("本期参与：" + my_buy_count + "次");
				result = (join / all) * 100;
				progressBarPeople.setMax(100);
				progressBarPeople.setProgress((int) result);
				double winProbability = (my / all) * 100;
				String win = String.format("%.2f", winProbability);// 转化保留两位小数
				tv_winProbability.setText("中奖概率：" + win + "%");
				if (joinNeed.equals(joinCount)) {
					Log.e("done===", "done");
					rl_doing.setVisibility(View.GONE);
					rl_done.setVisibility(View.VISIBLE);
				} else {
					// Log.e("doing===", "doing");
					rl_doing.setVisibility(View.VISIBLE);
					rl_done.setVisibility(View.GONE);
				}
			}
			if (my_buy_count != null) {
				tv_luckNum.setText("幸运号：" + my_sole_numbers);
			}
			// 请求完数据后
			ptr_view.refreshComplete();
		}

		@Override
		public void onRequestPrepare() {
			// TODO Auto-generated method stub
			super.onRequestPrepare();
		}

		@Override
		public void onRequestFailed(String error) {
			// TODO Auto-generated method stub
			super.onRequestFailed(error);
		}

	}

	@OnClick({ R.id.btn_nowJoin, R.id.btn_joinCarts, R.id.btn_Join_next })
	private void OnClick(View v) {
		switch (v.getId()) {
		case R.id.btn_joinCarts:// 加入购物车
			int all = Integer.parseInt(joinNeed);
			int count = Integer.parseInt(joinCount);
			if (count < all) {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("user_id", userid);
				map.put("gp_id", gp_id);
				map.put("number", "1");
				RequestTask.getInstance().doAddCarts(this, map,
						new onAddRequestListener());
				// RequestTask.getInstance().doAddCarts((Activity) context,
				// map,new onAddCartsRequestListener());
			} else {
				ToastUtils.show(context, "商品数量不足");
			}
			break;
		case R.id.btn_nowJoin:// 立即参与
			Bundle bundle = new Bundle();
			bundle.putString("flag", "参与详情页面");
			bundle.putString("title", title);
			bundle.putString("goodsName", goodsName);
			bundle.putString("allNeed", joinNeed);
			bundle.putString("joinCount", joinCount);
			bundle.putDouble("progress", result);
			bundle.putString("gp_id", gp_id);
			bundle.putString("description", introduct);
			openActivity(NowJoinActivity.class, bundle);
			break;

		case R.id.btn_Join_next:// 参与下一期
			Log.e("next_gp_id===1", next_gp_id);
			if (!next_gp_id.equals("") && !next_gp_id.equals("null")) {
				Log.e("next_gp_id===2", next_gp_id);
				Intent intent = new Intent();
				Bundle bundle_next = new Bundle();
				bundle_next.putString("gp_id", next_gp_id);
				intent.putExtras(bundle_next);
				intent.setClass(context, GoodsDetailActivity.class);
				context.startActivity(intent);
			}
			break;
		default:
			break;
		}
	}

	private class onAddRequestListener extends OnRequestListenerAdapter<Object> {
		public void onDone(XDroidRequest<?> request, String response,
				DataType dataType) {
			// TODO Auto-generated method stub
			super.onDone(request, response, dataType);
			// ToastUtils.show(JoinDetailActivity.this, "获取请求...");
			JsonData jsonData = JsonData.create(response);
			String data = jsonData.optString("code");
			if (data.equals("1")) {
				int count = jsonData.optInt("my_goods_count");
				EventFactory.sendUpdateCartCount(count);
				ToastUtils.show(JoinDetailActivity.this, "加入成功");
				// shoppingcarts.setImageResource(R.drawable.button_hot_shopping_cart_red);
			}
			if (data.equals("0")) {
				ToastUtils.show(JoinDetailActivity.this, "数量不足");
			}
		}
	}

}
